package com.aramis.mydytt.ui.detail

import androidx.lifecycle.MutableLiveData
import com.aramis.mydytt.db.*
import com.aramis.mydytt.ext.logD
import com.aramis.mydytt.ext.logE
import com.aramis.mydytt.ui.base.BaseViewModel
import com.aramis.mydytt.ui.bean.*
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers

/**
 * Description: MovieDetailViewModel
 * @author lizhidan
 * Created: 2021/4/7
 */
class MovieDetailViewModel : BaseViewModel() {
    val detailLiveData = MutableLiveData<MovieDetailBean?>()
    val commentLiveData = MutableLiveData<List<MovieCommentBean>?>()
    val dyttMovieDetailLiveData = MutableLiveData<DyttMovieDetailBean?>()
    val favoriteCheckLiveData = MutableLiveData<FavoriteMovieBean?>()
    val downloadedLiveData = MutableLiveData<DownloadedMovieBean>()

    //标记或取消标记喜欢
    fun addOrRemoveFavorite(favoriteMovieBean: FavoriteMovieBean?, movieItemBean: MovieItemBean) {
        if (favoriteMovieBean == null) {//标记喜欢
            compositeDisposable.add(FavoriteManager.addFavorite(movieItemBean).subscribe({
                if (it != null) {
                    logE("喜欢标记成功")
                    favoriteCheckLiveData.postValue(it)
                }
            }, {
                logE("喜欢标记失败 ${it.message}")
            }))
        } else {//取消标记
            compositeDisposable.add(FavoriteManager.removeFavorite(favoriteMovieBean.id).subscribe({
                if (it != null) {
                    logE("喜欢取消成功")
                    favoriteCheckLiveData.postValue(null)
                }
            }, {
                logE("喜欢取消失败 ${it.message}")
            }))
        }
    }

    //初始化检查此影片是否被标记成了喜欢
    fun checkFavorite(movieId: String) {
        DBManager.db?.favoriteMovieDao()?.selectByMovieId(movieId)?.subscribeOn(Schedulers.io())?.subscribe({
            favoriteCheckLiveData.postValue(it)
        }, {
            favoriteCheckLiveData.postValue(null)
        })?.let {
            compositeDisposable.add(it)
        }
    }

    //标记已下载
    fun markDownloaded(movieItemBean: MovieItemBean) {
        val downloadedMovieBean = movieItemBean.toDownloadedMovieBean()
        DownloadedManager.addDownloaded(downloadedMovieBean)?.subscribe({
            downloadedLiveData.postValue(it)
        }, {
            downloadedLiveData.postValue(null)
        })?.let {
            compositeDisposable.add(it)
        }
    }

    //初始化检查此影片是否已经被下载过
    fun checkDownLoaded(movieId: String) {
        DBManager.db?.downloadedMovieDao()?.selectByMovieId(movieId)?.subscribeOn(Schedulers.io())?.subscribe({
            downloadedLiveData.postValue(it)
        }, {
            downloadedLiveData.postValue(null)
        })?.let {
            compositeDisposable.add(it)
        }
    }

    //电影详情数据
    fun getMovieDetail(bean: MovieItemBean) {
        compositeDisposable.add(
            movieApi.getMovieDetail(bean.id).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe({
                detailLiveData.postValue(if (it.dataNotNull()) it.data else null)
                getCommentList(it?.data?.btbo_downlist)
            }, {
                logE("电影详情错误：${it.message}")
                detailLiveData.postValue(null)
            })
        )
        searchMovieByDytt(bean.title)
    }

    //评论列表数据
    private fun getCommentList(downloadList: List<MovieDetailDownListBean>?) {
        if (downloadList == null || downloadList.isEmpty() || downloadList[0].id <= 0) {
            commentLiveData.postValue(null)
            return
        }
        val urlId: String = downloadList[0].id.toString()
        compositeDisposable.add(
            movieApi.getCommentList(urlId).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe({
                logD("电影详情评论：${it}")
                commentLiveData.postValue(it?.data)
            }, {
                logE("电影详情评论错误：${it.message}")
            })
        )
    }

    //电影天堂的搜索
    private fun searchMovieByDytt(movieName: String) {
        compositeDisposable.add(
            dyttApi.search(movieName).subscribeOn(Schedulers.io()).subscribe({
                logE("电影天堂搜索成功：${it}")
                if (it?.rows != null && it.rows.isNotEmpty()) {
                    detailDytt(it.rows[0])
                }
            }, {
                logE("电影天堂搜索错误：${it.message}")
            })
        )
    }

    private fun detailDytt(bean: MovieShortInfoBean) {
        compositeDisposable.add(
            dyttApi.detail(bean.id, bean.categoryId).subscribeOn(Schedulers.io()).subscribe({
                logE("电影天堂影片详情成功：${it}")
                it.downloadUrl?.split("")
                dyttMovieDetailLiveData.postValue(it)
            }, {
                logE("电影天堂影片详情错误：${it.message}")
            })
        )
    }
}